#include "node_rendertarget.h"
#include "xge.h"
#include "scene_mgr.h"
#include "xsys_log.h"
#include "node_rootnode.h"
#include "g_graphics.h"


namespace xge{
namespace graphics{

  RenderTargetNode::RenderTargetNode( size_t width , size_t height ) {
    render_target_ = XGameEngine::GetGraphics2D()->CreateRenderTarget(width,height);
    if( render_target_ == NULL ) {
      // Can not create render target node here
      SYS_LOG(PANIC,true,_xT("Can not create render target node!"));
      return;
    }
    // Now we should setting the sprite node's parameter 
    // Setting up the dummy texture pointer
    // here is the things , this fake texture pointer has really been
    // constructed as the texture pointer , however we will not calling
    // its destructor so its internal reference count will never be
    // zero !
    TexturePtr* fake_tp_ptr = new (&fake_texture_ptr_) TexturePtr(render_target_->GetTexture());
    set_texture(*fake_tp_ptr);
    set_texture_rect( Rect(0.0f,0.0f,(float)width,(float)height) );
    set_blending(BLEND_DEFAULT);
    set_z(1.0f);
    set_color( Color::kBlack );
  }

  RenderTargetNode::~RenderTargetNode() {
    if( render_target_ )
      XGameEngine::GetGraphics2D()->DestroyRenderTarget(render_target_);
  }


  void RenderTargetNode::OnPaint( const Timer::tick_t& time_diff ) {
    // On Painting rendering here 
    // We should first setting up our rendering mode to enable the rendering
    TexturePtr* ptr = (TexturePtr*)(&fake_texture_ptr_);
    // Doing the nested rendering here 
    XGameEngine::GetSceneManager()->GetRootNode()->BeginScene(
      Graphics2D::MODE_NORMAL,Graphics2D::PRIMITIVE_QUAD,this,*ptr,blending());
    ListBaseNode::OnPaint(time_diff);
    XGameEngine::GetSceneManager()->GetRootNode()->EndScene();
    // Rendering self on the stuff here 
    SpriteNode::PaintSpriteOnly(time_diff);
  }
}
}
